package com.bilibili.juc.rwlock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/*
 * 1. ReadWriteLock : 读写锁
 *
 * 写写/读写 需要“互斥”
 * 读读 不需要互斥
 *
 */


class ReadWriteLockDemo2 {

   private volatile int number = 0;

   private ReadWriteLock lock = new ReentrantReadWriteLock();

   //读
   public void get() {
       lock.readLock().lock(); //上锁
       try {
           System.out.println(Thread.currentThread().getName() + " 读到了一个值: " + number);
       } finally {
           lock.readLock().unlock(); //释放锁
       }
   }

   //写
   public void set(int number) {
       lock.writeLock().lock();
       try {
           System.out.println(Thread.currentThread().getName() + "写入一个值" + number);
           this.number = number;
       } finally {
           lock.writeLock().unlock();
       }
   }
}

public class TestReadWriteLock {

    public static void main(String[] args) {
		ReadWriteLockDemo2 rw = new ReadWriteLockDemo2();

        new Thread(new Runnable() {
            @Override
            public void run() {
                int number = (int) (Math.random() * 101);
                rw.set(number);
            }
        }, "Write:").start();


        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    rw.get();
                }
            }).start();
        }
    }

}